//
//  YKDataViewController.m
//  YunKang
//
//  Created by leoking870 on 2017/9/24.
//  Copyright © 2017年 leoking870. All rights reserved.
//

#import "YKDataViewController.h"
#import "YKOrderDataViewController.h"
#import "YKPromoteDataViewController.h"
#import "YKRegionSaleModel.h"
#import "YKSearchDataByRegionViewController.h"
#import <NSDate+TFCore.h>
//#import <HorizontalBarChartView.h>
@import Charts;
@interface YKDataViewController ()<IChartAxisValueFormatter>
@property (nonatomic, strong)NSArray<YKRegionSaleModel*> *regionSummary;
@property (nonatomic, strong)HorizontalBarChartView *barChartView;
@end

@implementation YKDataViewController

- (void)loadData {
    [self tf_showStateView:kTFViewStateLoading];
    [TFHTTPMANAER POST:@"manage/regionSummary.htm" parameters:@{@"startDate":[NSString stringWithFormat:@"%zd-01-01",[[NSDate date]tf_year]],@"endDate":[[NSDate date] tf_dateStringWithFormat:@"yyyy-MM-dd"]} success:^(id responseObject) {
        
        [self.barChartView removeFromSuperview];
        
        self.regionSummary = [NSArray yy_modelArrayWithClass:[YKRegionSaleModel class] json:responseObject[@"regionSummary"]];
        self.regionSummary = [self.regionSummary subarrayWithRange:NSMakeRange(0, 10)];
        
        [self tf_showStateView:kTFViewStateNone];
        
        self.barChartView = [[HorizontalBarChartView alloc]initWithFrame:self.view.frame];
        
        [self.view addSubview:self.barChartView];
        
        [self.barChartView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.leading.trailing.equalTo(self.view);
            make.top.equalTo(self.view.mas_top).offset(30);
            make.bottom.equalTo(self.view.mas_bottom).offset(-50);
        }];
        
        //        self.barChartView.delegate = self;
        self.barChartView.chartDescription.enabled = NO;
        self.barChartView.drawGridBackgroundEnabled = NO;
        self.barChartView.dragEnabled = NO;
        [self.barChartView setScaleEnabled:NO];
        self.barChartView.pinchZoomEnabled = NO;
        self.barChartView.doubleTapToZoomEnabled = NO;
        self.barChartView.xAxis.labelPosition = XAxisLabelPositionBottom;
//        self.barChartView.rightAxis.enabled = NO;
        
        self.barChartView.drawBarShadowEnabled = NO;
        self.barChartView.drawValueAboveBarEnabled = YES;
        self.barChartView.maxVisibleCount = 60;
        
        ChartXAxis *xAxis = self.barChartView.xAxis;
        xAxis.labelPosition = XAxisLabelPositionBottom;
        xAxis.labelFont = [UIFont systemFontOfSize:10.f];
        xAxis.drawAxisLineEnabled = YES;
        xAxis.drawGridLinesEnabled = NO;
        xAxis.granularity = 1;
        xAxis.granularityEnabled = YES;
        xAxis.labelCount = self.regionSummary.count;
        xAxis.valueFormatter = self;
        
        ChartYAxis *leftAxis = self.barChartView.leftAxis;
        leftAxis.labelFont = [UIFont systemFontOfSize:10.f];
        leftAxis.drawAxisLineEnabled = YES;
        leftAxis.drawGridLinesEnabled = YES;
        leftAxis.axisMinimum = 0.0; // this replaces startAtZero = YES
        
        ChartYAxis *rightAxis = self.barChartView.rightAxis;
        rightAxis.enabled = YES;
        rightAxis.labelFont = [UIFont systemFontOfSize:10.f];
        rightAxis.drawAxisLineEnabled = YES;
        rightAxis.drawGridLinesEnabled = NO;
        rightAxis.axisMinimum = 0.0; // this replaces startAtZero = YES
        
        ChartLegend *l = self.barChartView.legend;
        l.horizontalAlignment = ChartLegendHorizontalAlignmentLeft;
        l.verticalAlignment = ChartLegendVerticalAlignmentBottom;
        l.orientation = ChartLegendOrientationHorizontal;
        l.drawInside = NO;
        l.form = ChartLegendFormSquare;
        l.formSize = 8.0;
        l.font = [UIFont fontWithName:@"HelveticaNeue-Light" size:11.f];
        l.xEntrySpace = 4.0;
        
        self.barChartView.fitBars = YES;
        
        double barWidth = 1;
        double spaceForBar = 2;
        
        NSMutableArray *yVals = [[NSMutableArray alloc] init];
        
        for (int i = 0; i < self.regionSummary.count; i++)
        {
            YKRegionSaleModel *model = self.regionSummary[i];
            BarChartDataEntry *entry = [[BarChartDataEntry alloc] initWithX:i * spaceForBar y:model.SALES];
            [yVals addObject:entry];
        }
        BarChartDataSet *set1 = [[BarChartDataSet alloc] initWithValues:yVals label:@"销售额(万元)"];
        set1.valueFormatter = self;
        set1.drawIconsEnabled = YES;
        
        NSMutableArray *dataSets = [[NSMutableArray alloc] init];
        [dataSets addObject:set1];
        
        BarChartData *data = [[BarChartData alloc] initWithDataSets:dataSets];
        [data setValueFont:[UIFont fontWithName:@"HelveticaNeue-Light" size:10.f]];
        data.barWidth = barWidth;
        
        self.barChartView.data = data;
        
        
        
        
    } failure:^(id responseObject, NSError *error) {
        [self tf_showStateView:kTFViewStateNetError];
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"图表展示";
    
    UILabel *titleLabel = [[UILabel alloc]init];
    titleLabel.text = @"本年度销售额统计表";
    [self.view addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(8);
        make.centerX.equalTo(self.view.mas_centerX);
    }];
    titleLabel.font = [UIFont boldSystemFontOfSize:16];
    
    
    UIButton *confirmButton = [[UIButton alloc]init];
    [confirmButton setTitle:@"查询明细" forState:UIControlStateNormal];
    [confirmButton setBackgroundColor:TFSTYLE(buttonEnableBackgroundColor)];
    [confirmButton setTitleColor:TFSTYLE(buttonEnableTitleColor) forState:UIControlStateNormal];
    [self.view addSubview:confirmButton];
    [confirmButton addTarget:self action:@selector(onSearchDetailTapped:) forControlEvents:UIControlEventTouchUpInside];
    [confirmButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.bottom.trailing.equalTo(self.view);
        make.height.mas_equalTo(40);
    }];
    confirmButton.titleLabel.font = [UIFont systemFontOfSize:14];
    
    [self loadData];
}

- (void)onSearchDetailTapped:(id)sender {
    YKSearchDataByRegionViewController *vc = [[YKSearchDataByRegionViewController alloc]init];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

- (NSString *)stringForValue:(double)value axis:(ChartAxisBase *)axis {
    NSLog(@"value:%f", value);
    if ((int)value >= 0 && (int)value/2 < self.regionSummary.count) {
        return [self.regionSummary[(int)value/2] REGION_NAME];
    }
    return @"";
}

- (NSString *)stringForValue:(double)value
                       entry:(ChartDataEntry *)entry
                dataSetIndex:(NSInteger)dataSetIndex
             viewPortHandler:(id)viewPortHandler{
    return [NSString stringWithFormat:@"%.2f", value];
}

- (void)onButton1Tapped:(id)sender {
    YKOrderDataViewController *vc = [[YKOrderDataViewController alloc]init];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)onButton2Tapped:(id)sender {
    YKPromoteDataViewController *vc = [[YKPromoteDataViewController alloc]init];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

- (UIView *)viewForTitle:(NSString *)title color:(UIColor *)color image:(UIImage*)image buttonColor:(UIColor *)buttonColor selector:(SEL)selector{
    UIView *view = [[UIView alloc]init];
    UILabel *performanceLabel = [[UILabel alloc]init];
    performanceLabel.textAlignment = NSTextAlignmentCenter;
    performanceLabel.text = title;
    performanceLabel.backgroundColor = color;
    [view addSubview:performanceLabel];
    [performanceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.top.trailing.equalTo(view);
        make.height.mas_equalTo(45);
    }];
    
    UIButton *button = [[UIButton alloc]init];
    [button setTitle:@"查看报表" forState:UIControlStateNormal];
    [button setTitleColor:buttonColor forState:UIControlStateNormal];
    button.layer.borderColor = buttonColor.CGColor;
    button.layer.borderWidth = 1;
    button.layer.cornerRadius = 2;
    button.titleLabel.font = [UIFont systemFontOfSize:14];
    button.layer.masksToBounds = YES;
    [view addSubview:button];
    [button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.equalTo(performanceLabel.mas_trailing).offset(-15);
        make.centerY.equalTo(performanceLabel.mas_centerY);
    }];
    [button setContentEdgeInsets:UIEdgeInsetsMake(2, 2, 2, 2)];
    [button addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside];
    UIImageView *imageView = [[UIImageView alloc]initWithImage:image];
    [view addSubview:imageView];
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.bottom.trailing.equalTo(view);
        make.top.equalTo(performanceLabel.mas_bottom);
    }];
    return view;
}


@end
